﻿using System;

namespace UtilZ.Dotnet.Ex.Base
{
    /// <summary>
    /// String类型转换接口
    /// </summary>
    public class StringTypeConverter : TypeConverterAbs
    {

        /// <summary>
        /// 构造函数
        /// </summary>
        public StringTypeConverter()
            : base(typeof(string))
        {

        }


        /// <summary>
        /// 转换数据到
        /// </summary>
        /// <param name="targetValueType">要待转换的目标类型</param>
        /// <param name="value">要转换的值</param>
        /// <param name="result">转换后的值,存放在object中,如果转换失败为目标类型的默认值</param>
        /// <returns>转换成功返回true,失败返回false</returns>
        protected override bool PrimitiveTryConvertTo(Type targetValueType, object value, out object result)
        {
            try
            {
                if (value == null)
                {
                    result = null;
                }
                else
                {
                    if (value is string)
                    {
                        result = value;
                    }
                    else
                    {
                        result = value.ToString();
                    }
                }

                return true;
            }
            catch (Exception ex)
            {
                ZLog.ZLoger.Warn(ex);
                result = null;
                return false;
            }
        }


        /// <summary>
        /// 尝试将字符串转换为值类型数据,包括枚举
        /// </summary>
        /// <param name="targetType">要待转换的目标类型</param>
        /// <param name="value">要转换的值</param>
        /// <param name="result">转换结果</param>
        /// <param name="style">字符串中数值样式[数字样式为NumberStyles值之一，日期时间为DateTimeStyles值之一,默认null为不使用样式]</param>
        /// <param name="formatProvider">一个提供区域性特定的格式设置信息的对象</param>
        /// <returns>转换成功返回true,失败返回false</returns>
        protected override bool PrimitiveTryConvertTo(Type targetType, string value, out object result, object style = null, IFormatProvider formatProvider = null)
        {
            result = value;
            return true;
        }




#if CORE

        /// <summary>
        /// 尝试将字符串转换为值类型数据,包括枚举
        /// </summary>
        /// <param name="targetType">要待转换的目标类型</param>
        /// <param name="value">要转换的值</param>
        /// <param name="result">转换结果</param>
        /// <param name="style">字符串中数值样式[数字样式为NumberStyles值之一，日期时间为DateTimeStyles值之一,默认null为不使用样式]</param>
        /// <param name="formatProvider">一个提供区域性特定的格式设置信息的对象</param>
        /// <returns>转换成功返回true,失败返回false</returns>
        protected override bool PrimitiveTryConvertTo(Type targetType, ReadOnlySpan<char> value, out object result, object style = null, IFormatProvider formatProvider = null)
        {
            result = new string(value);
            return true;
        }
#endif

    }
}
